<template>
  <div class="login">
    <div class="loginbox">
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="0px" class="login_From">
        <!-- 账号 -->
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone">
            <i slot="prefix" class="el-input__icon el-icon-user-solid"></i>
          </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password">
            <i slot="prefix" class="el-input__icon el-icon-s-cooperation"></i>
            <el-button slot="append" @click="resetPassword">
            <template>重置密码</template>
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="danger" @click="login">登录</el-button>
          <el-button>注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        phone: '15079962544',
        password: '123456xgq'
      },
      loginRules: {
        // 验证账号是否合法
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 3, max: 11, message: '账号长度应在11个字符', trigger: 'blur' }
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度应在6-12个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetPassword() {
      this.$refs.loginFormRef.resetFields()
    },
    login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) {
          return alert('账号或密码不合法！')
        }
        const { data: res } = await this.$http.post('/login/cellphone', this.loginForm)
        if (res.code !== 200) {
          return this.$message.error('登录失败！', res.msg)
        }
        this.$message.success('登录成功')
        console.log(res)
        window.sessionStorage.setItem('cookie', res.cookie)
        window.sessionStorage.setItem('profile', JSON.stringify(res.profile))

        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped>
.login {
  height: 100%;
  background-color: #ddd;
}
.loginbox {
  width: 450px;
  height: 300px;
  background-color: #ffffff;
  border-radius: 6px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.login_From {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
.btns {
  display: flex;
  justify-content: center;
}
</style>
